import React, { useEffect, useRef, useState } from 'react'
import { Button, Table, Modal, Switch } from 'antd'
import axios from 'axios'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UserForm from '../../../components/user-manage/UserForm'

const { confirm } = Modal

export default function UserList() {
  // dataSource拿到的所有数据；初始值时一个空数组 通过后端数据拿到
  const [dataSource, setdataSource] = useState([])
  const [isAddOpen, setisAddOpen] = useState(false)
  const [isUpdateOpen, setisUpdateOpen] = useState(false)
  const [regionList, setregionList] = useState([])
  const [roleList, setroleList] = useState([])
  const [current,setcurrent] = useState(null)


  const addForm = useRef(null) //与UserFor子组件传递
  const updateForm = useRef(null) 
  const [isUpdateDisabled,setisUpdateDisabled] = useState(false)

  //拿到后端数据渲染到页面
  useEffect(() => {
    axios.get("http://localhost:5000/users?_expand=role").then(res => {
      // console.log(res.data);
      const list = res.data
      setdataSource(list)
    })
  }, [])

  //区域
  useEffect(() => {
    axios.get("http://localhost:5000/regions").then(res => {
      const list = res.data
      setregionList(list)
    })
  }, [])

  //角色
  useEffect(() => {
    axios.get("http://localhost:5000/roles").then(res => {
      const list = res.data
      setroleList(list)
    })
  }, [])

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      // 定义样式用render是一个函数
      render: (region) => {
        return <b>{region === "" ? '全球' : region}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role.roleName
      }
    },
    {
      title: '账号名',
      dataIndex: 'username',
    },
    {
      title: '账号状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch checked={roleState} disabled={item.default} onClick={()=>handleChange(item)}></Switch>
      }
    },
    {
      title: '操作',
      render: (item) => { //在操作项中传入形参一层一层传入为下面点击删除拿到数据
        return <div>
          <Button danger shape='round' icon={<DeleteOutlined />}
            onClick={() => confirmMethod(item)}
            disabled={item.default}
          ></Button>

          <Button type="primary" shape='round' icon={<EditOutlined />}
            disabled={item.default}
            onClick={()=>handleUpdate(item)}
          ></Button>

        </div>
      }
    },
  ];


  //确认删除提示操作
  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }

  //点击删除执行此方法 (在操作项中传入形参拿到点击删除时的数据)
  const deleteMethod = (item) => {
    // console.log(item);
    //删除后要当前页面同步状态 + 后端数据也要同步
    setdataSource(dataSource.filter(data=>data.id!==item.id))
    axios.delete(`http://localhost:5000/users/${item.id}`)
  }

  //添加用户校验成功后操作
  const addFormOK = () => {
    // 成功收集.then 出问题.catch
    addForm.current.validateFields().then(value => {
      // console.log(value);
      //模态框消失
      setisAddOpen(false)
      //模态kuang重置
      addForm.current.resetFields()
      //先post到后端，生成ID在设置dataSource，方便后面的删除和更新用户处理
      axios.post(`http://localhost:5000/users`, {
        ...value,
        "roleState": true,
        "default": false,
      }).then(res=>{
        console.log(res.data);
        //先把牢数据展开 再把新数据坊进去
      setdataSource([...dataSource,{
        ...res.data,
        role:roleList.filter(item=>item.id===value.roleID)[0]
      }])
      })
    }).catch(err => {
      console.log(err);
    })
  }

//Switch账号状态开关,
  const handleChange = (item)=>{
    // console.log(item);
    item.roleState = !item.roleState
    setdataSource([...dataSource])

    axios.patch(`http://localhost:5000/users/${item.id}`,{
      roleState : item.roleState 
    })
  }
//点击出现模态框...
  const handleUpdate = (item)=>{
    //react中状态的更新，不保证时同步的(放在一个异步中)
    // setFieldsValue  ref表单实例上的一个方法可以动态设定表单的值
    setisUpdateOpen(true)
    setTimeout(()=>{
      
      if(item.roleID===1){
        //禁用
        setisUpdateDisabled(true)
      }else{
        //取消禁用
        setisUpdateDisabled(false)
      }
      updateForm.current.setFieldsValue(item)
    },0)

    setcurrent(item)
  }

  const updateFormOK = ()=>{
    updateForm.current.validateFields().then(value => {
            // console.log(value)
            setisUpdateOpen(false)
            setdataSource(dataSource.map(item => {
                if (item.id === current.id) {
                    return {
                        ...item,
                        ...value,
                        role: roleList.filter(data => data.id === value.roleId)[0]
                    }
                }
                return item
      }))
      // setisUpdateDisabled(!isUpdateDisabled)
      axios.patch(`http://localhost:5000/users/${current.id}`,value)
    })
  }

  return (
    <div>
      <Button type='primary' onClick={() => {
        setisAddOpen(true)
      }}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns}
        pagination={{ pageSize: 5 }}
        rowKey={item => item.id}
      />

      <Modal
        open={isAddOpen}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddOpen(false)
        }}
        onOk={() => addFormOK()}
      >
        {/*ref={addForm} 把UserList父组件的ref对象传递到子组件 */}
        <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
      </Modal>

      <Modal
        open={isUpdateOpen}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateOpen(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()}
      >
        <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled}></UserForm>
      </Modal>

    </div>
  )
}
